package io.gitee.hefren.hhconfigserver.service.impl;

import com.google.common.collect.Lists;
import io.gitee.hefren.hhconfigserver.beans.Configs;
import io.gitee.hefren.hhconfigserver.dao.HhConfigServerMapper;
import io.gitee.hefren.hhconfigserver.service.HhConfigServerService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @Date 2024/5/26
 * @Author lifei
 */
@Service
public class HhConfigServerServiceImpl implements HhConfigServerService {

    @Resource
    private HhConfigServerMapper hhConfigServerMapper;


    @Override
    public List<Configs> findConfigsList(String capp, String cenv, String cnamespace) {
        List<Configs> result = Lists.newArrayList();
        List<Configs> configsList = hhConfigServerMapper.findConfigsList(capp, cenv, cnamespace);
        if (Objects.nonNull(configsList) && !configsList.isEmpty()) {
            result.addAll(configsList);
        }
        return result;
    }

    @Override
    public List<Configs> updateOrInsertConfigsList(String capp, String cenv, String cnamespace, Map<String, String> kvMap) {
        List<Configs> result = Lists.newArrayList();
        if (Objects.isNull(kvMap) || kvMap.isEmpty()) {
            return result;
        }
        updateOrInsertConfigsVersion(capp, cenv, cnamespace, System.currentTimeMillis());
        List<Configs> list = kvMap.keySet().stream().map(ckey -> new Configs(capp, cenv, cnamespace, ckey, kvMap.get(ckey))).toList();
        for (Configs configs : list) {
            Configs oldConfigs = hhConfigServerMapper.findConfigs(capp, cenv, cnamespace, configs.getCkey());
            if (Objects.isNull(oldConfigs) || Objects.isNull(oldConfigs.getCkey())) {
                hhConfigServerMapper.insertConfigs(configs);
            } else {
                hhConfigServerMapper.updateConfigs(configs);
            }
        }
        return findConfigsList(capp, cenv, cnamespace);
    }

    @Override
    public Long updateOrInsertConfigsVersion(String capp, String cenv, String cnamespace, Long cversion) {
        Long oldVersion = hhConfigServerMapper.findConfigsVersion(capp, cenv, cnamespace);
        if (Objects.isNull(oldVersion)) {
            hhConfigServerMapper.insertConfigsVersion(capp, cenv, cnamespace, cversion);
        } else {
            hhConfigServerMapper.updateConfigsVersion(capp, cenv, cnamespace, cversion);
        }
        return cversion;
    }

    @Override
    public Long findConfigsVersion(String capp, String cenv, String cnamespace) {
        Long cVersion = hhConfigServerMapper.findConfigsVersion(capp, cenv, cnamespace);
        return Optional.ofNullable(cVersion).orElse(-1L);
    }
}
